<template>
  <section>
    <el-row>
      <el-col :span="24">
        <!--表单-->
          <el-button type="primary" style="float:right;margin-bottom: 22px;" @click="handledit('add')" id="addUser">创建管理员</el-button>
        <!--表格-->
        <el-table
          :data="tableData.slice((currentPage - 1) * 10, currentPage * 10)"
          border
          style="width: 100%">
          <el-table-column
            prop="username"
            label="用户名"
            width="90">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
            width="100">
          </el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            width="90">
          </el-table-column>
          <el-table-column
            prop="email"
            label="邮箱"
            width="180">
          </el-table-column>
          <el-table-column
            prop="age"
            label="年龄"
            width="40">
          </el-table-column>
          <el-table-column
            prop="sex"
            label="性别"
            width="40" :formatter="formatSex">
          </el-table-column>
          <el-table-column
            prop="avatar"
            label="头像"
            width="180">
            <template scope="scope">
                    <img :src="scope.row.avatar" width="90" height="90"/>
            </template>
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="创建时间"
            width="180" :formatter="formatCreateTime">
          </el-table-column>
          <el-table-column
            prop="cname"
            label="公司名称"
            width="180">
          </el-table-column>
          <el-table-column label="">
            <template scope="scope">
              <el-button type="primary" size="small" @click="handledit('update', scope.row)">编辑</el-button>
              <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">角色</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="10"
            layout="prev, pager, next, jumper"
            :total="tableData.length">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <edit
      :visible.sync="editVisible"
      :user="user"
      :operation="operation"
      @confirm="confirm"
    />
      <user-edit-role ref="mychild"
      :visible.sync="editRoleVisible"
      :roleList="roleList"
      @confirm="confirmRole"
    />
  </section>
</template>
<script type="text/ecmascript-6">
import debounce from 'lodash.debounce';
import { organizationUserService } from '@/services';
import utils from '@/utils.js';
import Edit from '@/views/organization/user/userEdit';
import userEditRole from '@/views/organization/user/userRoleEdit';
export default {
  data () {
    return {
      tableData: [],
      currentPage: 1,
      editVisible: false,
      editRoleVisible : false,
      user: {},
      role_user_id: null,
      operation: 'add',
      chooseRoleList: [],
      roleList: [],
    };
  },
  components: { Edit, userEditRole },
  activated () {
    this.getUserList();
  },
  watch:{
      editRoleVisible(val, oldVal){//普通的watch监听
          if(val==true){
            this.$refs.mychild.setChooseRoles(this.roleList);
          }
      },
  },
  methods: {
    getUserList: debounce(async function() {
      this.tableData = await organizationUserService.getUserList();
    }, 500),
    async getRoleList (user_id) {
       try {
         this.roleList = await organizationUserService.getUserRole(user_id);
         this.editRoleVisible = true;
       } catch (e) {
         console.log(e);
       }
    },
    formatCreateTime(row, column) {
      return utils.timestampToTime(row.create_time*1000);
    },
    formatSex(row, column) {
      if(row.sex==1){
        return "男";
      }else if(row.sex==2){
        return "女";
      }else {
        return "不详";
      }
      
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      if (process.env.NODE_ENV !== 'production') {
      // eslint-disable-next-line
        console.log(`当前页: ${val}`);
      }
    },
   async handleDelete (index, row) {
      try {
        await this.$confirm('是否确认删除此管理员?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
       await organizationUserService.deleteUser(row.user_id);
        this.$message({
          message: '删除成功,账号已锁定',
          type: 'success'
        });
        this.getUserList();
      } catch (e) {
        console.error(e);
      }
    },
    handleRole (index, user) {
      this.role_user_id = user.user_id;
      this.getRoleList(user.user_id);
    },
    handledit(operation, user) {
      const _user = {
        username: '',
        password: '',
        nickname: '',
        phone: '',
        email: '',
        avatar: '',
        age: 0,
        sex: 0,
      };
      this.editVisible = true;
      this.operation = operation;
      this.user = user ? Object.assign({}, user) : _user;
    },
    async confirm() {
      try {
          if (this.operation === 'add') {
            await organizationUserService.addUser(this.user);
            this.$message({message:'添加成功',type:'success'});
          } else {
            console.log(this.user);
            await organizationUserService.editUser(this.user);
            this.$message({message:'编辑成功',type:'success'});
          }
          this.getUserList();
          this.editVisible = false;
      } catch (error) {
        console.log(error);
      }
    },
    async confirmRole (chooseRoles) {
      try {
        this.editRoleVisible = false;
        var da = chooseRoles.join(',');
        await organizationUserService.editUserRole(this.role_user_id,da);
        this.$message({type: 'success',message: '编辑成功'});
      } catch (error) {
        console.log(error);
      }
    }
  }
};
</script>
<style>
  .el-pagination {
    text-align: center;
    margin-top: 30px;
  }
  .el-message-box__btns .cancel {
    float: right;
    margin-left: 10px;
  }
</style>